package com.xiaotao.service.impl;

import com.xiaotao.entity.UserSign;
import com.xiaotao.entity.Wallet;
import com.xiaotao.mapper.UserSignMapper;
import com.xiaotao.mapper.WalletMapper;
import com.xiaotao.service.UserSignService;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import com.xiaotao.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserSignServiceImpl implements UserSignService {
    @Resource
    private UserSignMapper userSignMapper;
    @Resource
    private WalletMapper walletMapper;
    @Override
    public ResponseUtil add(UserSign userSign) throws Exception {
        Integer userId = UserUtil.UserContext();
        userSign.setUserId(userId);
        UserSign todaySign = userSignMapper.queryByIdAndDate(userId, new Date());
        if (todaySign != null && todaySign.getStatus() == 1) {
            return ResponseUtil.get(ResponseEnum.FAIL, "今日已签到，无需重复操作");
        }
        Wallet wallet = walletMapper.queryByUserId(userId);
        wallet.setPoints(wallet.getPoints()+50);
        walletMapper.addPoint(wallet);
        Integer add = userSignMapper.add(userSign);
        return add>0 ? ResponseUtil.get(ResponseEnum.OK):
                ResponseUtil.get(ResponseEnum.FAIL);
    }
    @Override
    public ResponseUtil queryByIdAndDate(Integer userId, Date date) throws Exception {
        userId = UserUtil.UserContext();
        UserSign userSign = userSignMapper.queryByIdAndDate(userId, date);
        return userSign!=null ? ResponseUtil.get(ResponseEnum.OK):
                ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil queryAll(Integer userId) throws Exception {
        List<UserSign> userSigns = userSignMapper.queryAll(userId);
        return userSigns!=null ? ResponseUtil.get(ResponseEnum.OK,userSigns):
                ResponseUtil.get(ResponseEnum.FAIL);
    }
}
